package com.wang.designpattern.singleton.type4;

public class SingletonTest04 {

    public static void main(String[] args) {
        System.out.println("双重检查（线程安全，懒加载）");
        Singleton singleton1 = Singleton.getInstance();
        Singleton singleton2 = Singleton.getInstance();
        System.out.println(singleton1 == singleton2);
        System.out.println("singleton1.hashCode() == " + singleton1.hashCode());
        System.out.println("singleton2.hashCode() == " + singleton2.hashCode());
    }

}

class Singleton {
    // 1、私有化构造函数，外部不能new
    private Singleton() {}

    // 2、私有化静态成员变量
    // volatile 变量可见性，防止代码重排
    private static volatile Singleton instance;


    // 4、提供一个公有的静态方法，返回对象，加入双重检查代码，解决线程安全问题，同时解决懒加载问题
    public static Singleton getInstance() {
        if (null == instance) {
            synchronized(Singleton.class) {
                if (null == instance) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}
